package com.gcb.common.utils.huawei;

import com.gcb.common.exception.ServiceException;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


/**
 * 存储对象管理
 */
@Slf4j
@Component
public class ObsUtils {


    /**
     * 本地文件流上传
     *
     * @param file
     * @return
     */
    public static String fileUpload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        ObsClient obsClient = new ObsClient(HuaweiConstant.AK, HuaweiConstant.SK, HuaweiConstant.ENDPOINT);
        try {
            PutObjectResult putObjectResult = obsClient.putObject(HuaweiConstant.BUCKET_NAME, fileName, file.getInputStream());
            log.info("上传文件到华为云OBS，返回结果：{}", putObjectResult.toString());
            if (putObjectResult.getStatusCode() == 200) {
                return putObjectResult.getObjectUrl();
            }else {
                log.error("上传文件到华为云OBS失败");
                throw new ServiceException("上传文件到华为云OBS失败");
            }
        } catch (Exception e) {
            log.error("上传文件失败：{}", e.getMessage());
            e.printStackTrace();
            throw new ServiceException("上传文件到华为云OBS失败");
        }
    }

}


